﻿#region Imports

using System;
using System.Collections.Generic;
using NHibernate;
using Spring.Data.NHibernate;
using Spring.Data.NHibernate.Generic.Support;
using d3PrtDgn.Core.BaseData;
using d3PrtDgn.Data.IDAO;
using d3PrtDgn.Data.Domain.Entity;

#endregion

namespace d3PrtDgn.Data.DAO
{
	/// <summary>
	/// Hibernate User DAO
	/// </summary>
    class UserDao : BaseDao, IUserDao
	{
		#region IUserDao Members

		/// <summary>
		/// Loads user by ID
		/// </summary>
		/// <param name="userId">Users ID</param>
		/// <returns>Loaded user</returns>
		public User FindById(int userId)
		{
			return HibernateTemplate.Load<User>(userId);
		}

		/// <summary>
		/// Loads all users
		/// </summary>
		/// <returns>Loaded users</returns>
		public IList<User> FindAll()
		{
			return HibernateTemplate.LoadAll<User>();
		}

		/// <summary>
		/// Saves user
		/// </summary>
		/// <param name="user">User to save</param>
		/// <returns>Saved user</returns>
		public User Save(User user)
		{
			HibernateTemplate.Save(user);
			return user;
		}

		/// <summary>
		/// Saves or updates (if already exists) user
		/// </summary>
		/// <param name="user">User to save or update</param>
		/// <returns>Saved or updated user</returns>
		public User SaveOrUpdate(User user)
		{
            return base.SaveOrUpdate(user) as User;
		}

		/// <summary>
		/// Deletes user
		/// </summary>
		/// <param name="user">User to delete</param>
		public void Delete(User user)
		{
            base.Delete(user);
		}

		/// <summary>
		/// Checks if user with specified username already exists
		/// </summary>
		/// <param name="username">Username to check</param>
		/// <returns>Flag if user with specified username exists</returns>
		public bool Exists(string username)
		{
			return HibernateTemplate.Find<User>("from User where username = ?", username).Count > 0;
		}

		/// <summary>
		/// Authenticates user - checks username and password
		/// </summary>
		/// <param name="user">User to authenticate</param>
		/// <returns>Authenticated user or null if not valid</returns>
		public User Authenticate(User user)
		{
			IList<User> found = HibernateTemplate.Find<User>("from User where username = ? and password = ?", new string[] { user.Username, user.Password });
			if (found.Count == 1) return found[0];

			return null;
		}

		#endregion
	}
}